<template>
  <view class="container">
    <m-header>
      <view class="headerPress" @click="chooseStore">
        <image class="headerIco" src="/static/assets/icon_i_dpxx.png" mode=""></image>
        <text class="headerTxt">{{store && store.role_name || '请选择'}}</text>
      </view>
    </m-header>
    <header-filler></header-filler>
    <!-- 搜索框 -->
    <!-- <search tips="搜索商品" @event="$navTo('pages/search/index')" /> -->
		
		<!-- banner -->
		<view class="banner" ref="banner">
			<Banner :itemStyle="banner.style" :params="banner.params" :dataList="banner.data"></Banner>
		</view>

    <!-- 主内容 -->
    <view class="cate-content dis-flex">

      <!-- 左侧 分类 -->
      <scroll-view class="cate-left" :scroll-y="true" :style="{ height: `${scrollHeight}px` }">
        <!-- <view class="menus" v-for="(item, idx) in sonTypes" :key="idx" @click="handleSelectSubNav(idx)" :class="{ selected: subIndex == idx }"> -->
        <view class="menus" v-for="(item, idx) in list" :key="idx" @click="handleSelectNav(idx)" :class="{ selected: curIndex == idx }">
          <view class="cate-img">
            <image v-if="item.image" mode="widthFix" :src="item.image.preview_url"></image>
          </view>
          <text class="tx">{{ item.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧  -->
			<view class="cate-right-wrap" :style="{ height: `${scrollHeight}px` }">
				<view class="cate-top">
				  <scroll-view scroll-x="true" class="cate-top-scroll">
				    <view class="menus" v-for="(item, idx) in sonTypes" :key="idx" @click="handleSelectSubNav(idx)" :class="{ selected: subIndex == idx }">
				      <text class="tx">{{ item.name }}</text>
				    </view>
				  </scroll-view>
				</view>
				<scroll-view class="cate-right b-f" :scroll-top="scrollTop" :scroll-y="true">
				  <!-- 商品列表 -->
				  <view class="goods-list clearfix">
				    <view class="goods-item" v-for="(item, index) in goodsList.data" :key="index" @click="onTargetDetail(item.goods_id)">
				      <!-- 商品图片 -->
				      <view class="goods-item_left">
				        <image class="image" :src="item.goods_image"></image>
                <image class="saleout" v-if="item.stock_total == 0" src="/static/assets/soldout.png" mode="scaleToFill"></image>
				      </view>
				      <view class="goods-item_right">
				        <!-- 商品名称 -->
				        <view class="goods-name onelist-hidden">
				          <text>{{ item.goods_name }}</text>
				        </view>
				        <view class="goods-item_desc">
				          <!-- 商品价格 -->
				          <view class="desc_footer" v-if="userId">
				            <text class="price_x">¥{{ item.goods_price_min }}</text>
				            <view class="btn"></view>
				          </view>
				        </view>
				      </view>
							
				    </view>
				  </view>
				  <!-- 商品列表 end -->
				</scroll-view>
			</view>
      
    </view>
    <empty v-if="!list.length" :isLoading="isLoading" />
    
    <float-service></float-service>
  </view>
</template>

<script>
  import config from '@/config'
  import { setCartTabBadge } from '@/utils/app'
  import SettingKeyEnum from '@/common/enum/setting/Key'
  import SettingModel from '@/common/model/Setting'
  import * as Api from '@/api/page'
  import * as CategoryApi from '@/api/category'
  import Search from '@/components/search'
  import Empty from '@/components/empty'
	import Banner from '@/components/page/banner'
  import * as GoodsApi from '@/api/goods'
	import * as LoginApi from '@/api/login'
  import { getEmptyPaginateObj, getMoreListData } from '@/utils/app'
  
  const pageSize = 15
  const App = getApp()

  export default {
    components: {
      Search,
      Empty,
			Banner
    },
    data() {
      return {
        config,
        // 列表高度
        scrollHeight: 0,
        // 一级分类：指针
        curIndex: 0,
        // 二级分类：指针
        subIndex: 0,
        // 内容区竖向滚动条位置
        scrollTop: 0,
				banner: {data: [], style: { interval: 2.5 }},
        // 分类列表
        list: [],
        //商品列表
        goodsList: getEmptyPaginateObj(), // 商品列表数据
        sortType: 'all', // 排序类型
        sortPrice: false, // 价格排序 (true高到低 false低到高)
        // 上拉加载配置
        upOption: {
          // 首次自动执行
          auto: true,
          // 每页数据的数量; 默认10
          page: { size: pageSize },
          // 数量要大于4条才显示无更多数据
          noMoreSize: 4,
        },
        // 分类模板设置
        templet: {},
        // 正在加载中
        isLoading: true
      }
    },
    computed: {
      sonTypes() {
        return this.list[this.curIndex] && this.list[this.curIndex].children ? this.list[this.curIndex].children.filter(item => item.image_banner_id < 1) : []
      },
      bannerItem () {
        let img = '';
        if (this.list[this.curIndex] &&  this.list[this.curIndex].children && this.list[this.curIndex].children[0].image_banner_id) {
          img = config.domain + 'uploads/' +this.list[this.curIndex].children[0].image_banner.file_path
        }
        return img
      },
      store() {
        return this.$store.state.app.store
      },
      userId() {
        return this.$store.state.user.userId
      }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
      const app = this
      // 设置分类列表高度
      app.setListHeight()
      
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      const app = this
      // 获取页面数据
      app.getPageData()
      // 更新购物车角标
      setCartTabBadge()
			
			LoginApi.getStoreList()
				.then(res => {
					this.$store.dispatch('SetStoreJSON', res.data.list)
					console.log(this.$store.state.app.storeJSON)
				})
    },

    methods: {
      chooseStore() {
        uni.navigateTo({
          url: '/pages/storelist/storelist'
        })
      },
			setCurrentCateId() {
				const cid = this.$store.state.app.cateId
        if (cid) {
          this.list.map((item, index) => {
          	if (item.category_id == cid) {
          		this.curIndex = index
          		this.subIndex = 0
          	}
          })
          this.$store.dispatch('SetCateId', '')
        }
			},
      /**
       * 获取页面数据
       */
      getPageData() {
        const app = this
        app.isLoading = true
				Api.detail({
				  pageId: 0,
				  role_id: this.store ? this.store.role_id: ''
				})
				  .then(result => {
				    // banner数据
				    const { data: { pageData } } = result
				    app.banner = pageData.items[0] && pageData.items[0].type === 'banner' ? pageData.items[0] : {data: []}
						
				  })
        Promise.all([
            // 获取分类模板设置
            // 优化建议: 可以将此处的false改为true 启用缓存
            SettingModel.data(false),
            // 获取分类列表
            CategoryApi.list()
          ])
          .then(result => {
            // 初始化分类模板设置
            app.initTemplet(result[0])
            // 初始化分类列表数据
            app.initCategory(result[1])
            
            app.getGoodsList(1)
          })
          .finally(() => app.isLoading = false)
      },

      /**
       * 初始化分类模板设置
       * @param {Object} result
       */
      initTemplet(setting) {
        this.templet = setting[SettingKeyEnum.PAGE_CATEGORY_TEMPLATE.value]
      },

      /**
       * 初始化分类列表数据
       * @param {Object} result
       */
      initCategory(result) {
        const app = this
        const data = result.data
        app.list = data.list
				app.setCurrentCateId()
      },

      /**
       * 设置分类列表高度
       */
      setListHeight() {
        const app = this
        uni.getSystemInfo({
          success(res) {
            console.log(res)
            app.scrollHeight = res.windowHeight - 44 - 90 - res.statusBarHeight
          }
        })
      },

      // 一级分类：选中分类
      handleSelectNav(index) {
        const app = this
        app.curIndex = index
        app.subIndex = 0
        app.scrollTop = 0
        app.getGoodsList(1)
      },
      
      //二级分类：选中
      handleSelectSubNav(index) {
        const app = this
        app.subIndex = index
        app.scrollTop = 0
        app.getGoodsList(1)
      },

      // 跳转至商品列表页
      onTargetGoodsList(categoryId) {
        this.$navTo('pages/goods/list', { categoryId })
      },
      
      // 跳转商品详情页
      onTargetDetail(goodsId) {
        this.$navTo('pages/goods/detail', { goodsId })
      },
      /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
        const app = this
        // 设置列表数据
        app.getGoodsList(page.num)
          .then(list => {
            const curPageLen = list.data.length
            const totalSize = list.data.total
          })
          .catch(() => app.mescroll.endErr())
      },
      
      /**
       * 获取商品列表
       * @param {number} pageNo 页码
       */
      getGoodsList(pageNo = 1) {
        const app = this
        let cid = this.sonTypes[this.subIndex] ? this.sonTypes[this.subIndex].category_id : 0
        if (this.sonTypes.length === 0) {
          cid = this.list[this.curIndex].category_id
        }
        const param = {
          sortType: app.sortType,
          sortPrice: Number(app.sortPrice),
          categoryId: cid || 0,
          goodsName: '',
          page: pageNo,
					role_id: this.store ? this.store.role_id: ''
        }
        return new Promise((resolve, reject) => {
          GoodsApi.list(param)
            .then(result => {
              // 合并新数据
              const newList = result.data.list
              app.goodsList.data = getMoreListData(newList, app.goodsList, pageNo)
              resolve(newList)
            })
            .catch(reject)
        })
      },
      

    },

    /**
     * 设置分享内容
     */
    onShareAppMessage() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/category/index?' + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/category/index?' + app.$getShareUrlParams()
      }
    }
    
    
  }
</script>

<style>
  page {
    background: #fff;
  }
</style>
<style lang="scss" scoped>
  @import "style.scss";
</style>
